/*
 * @author:她不美却常驻我心
 * @timer:2017-06-28
 * @email:1184112975@qq.com
 * @version:1.3
 * @title:封装一个自己常用的工具类js
 * @note: This js file is for the author's own use only
 */
var wang = {
    // 获取url参数
    getQueryString : function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if(r != null) return unescape(r[2]);
        return null;
    },
    // 获取或获取设置时间
    getData : function (x,y,z){
        var x , y , z ;
        if(arguments.length < 3){
            x = y = z = 0
        }
        var dd = new Date();
        dd.setYear(dd.getFullYear()+x); // x为当前的
        dd.setMonth(dd.getMonth()+y);
        dd.setDate(dd.getDate()+z);
        var y = dd.getFullYear();
        var m = dd.getMonth()+1;
        var d = dd.getDate();
        return y+"-"+wang.toDub(m)+"-"+wang.toDub(d);
    },
    // 获取年份
    getYear : function (){
        return  new Date().getFullYear();
    },
    // 获取月份
    getMonth : function (){
        return  new Date().getMonth()+1;
    },
    // 获取某个月份的天数
    getDays : function (year,month){
        return new Date(year, month, 0).getDate();
    },
    // 获取星期
    getWeek : function (){
        return  new Date().getDay();
    },
    // 获取今天是几号
    getDay : function (){
        return  new Date().getDate();
    },
    // URI 编码
    encodeURI : function (key){
        return encodeURI(key);
    },
    // URI 解码
    decodeURI : function (key){
        return decodeURI(key);
    },
    // json 去重
    uniqueArray : function (array,key){
        var result = [array[0]];
        for(var i = 1; i < array.length; i++){
            var item = array[i];
            var repeat = false;
            for (var j = 0; j < result.length; j++) {
                if (item[key] == result[j][key]) {
                    repeat = true;
                    break;
                }
            }
            if (!repeat) {
                result.push(item);
            }
        }
        return result;
    },
    // 数组去重
    removeRepeatArray: function(arr) {
        return arr.filter(function(item, index, self) {
            return self.indexOf(item) === index;
        });
        //es6
        //return Array.from(new Set(arr))
    },
    //设置cookie
    setCookie: function(name, value, iDay) {
        var oDate = new Date();
        oDate.setDate(oDate.getDate() + iDay);
        document.cookie = name + '=' + value + ';expires=' + oDate;
    },
    //获取cookie
    getCookie: function(name) {
        var arr = document.cookie.split('; ');
        for (var i = 0; i < arr.length; i++) {
            var arr2 = arr[i].split('=');
            if (arr2[0] == name) {
                return arr2[1];
            }
        }
        return '';
    },
    //删除cookie
    removeCookie: function(name) {
        this.setCookie(name, 1, -1);
    },
    //字符串替换(字符串,要替换的字符或者正则表达式（不要写g）,替换成什么)
    replaceAll: function(str, AFindText, ARepText) {
        raRegExp = new RegExp(AFindText, "g");
        return str.replace(raRegExp, ARepText);
    },
    /* 过滤字符串(html标签，表情，特殊字符)
     * 替换内容（special-特殊字符,html-html标签,emjoy-emjoy表情,word-小写字母，WORD-大写字母，number-数字,chinese-中文）
     * 过滤字符串的html标签，大写字母，中文，特殊字符，全部替换成*,但是特殊字符'%'，'?'，除了这两个，其他特殊字符全部清除
     * str	需要替换的内容	type	替换类型	restr	替换为	spstr	需要保留的
     */
    filterStr: function(str, type, restr, spstr) {
        var typeArr = type.split(','),
            _str = str;
        for (var i = 0, len = typeArr.length; i < len; i++) {
            //是否是过滤特殊符号
            if (typeArr[i] === 'special') {
                var pattern, regText = '$()[]{}?\|^*+./\"\'+';
                //是否有哪些特殊符号需要保留
                if (spstr) {
                    var _spstr = spstr.split(""),
                        _regText = "[^0-9A-Za-z\\s";
                    for (var j = 0, len1 = _spstr.length; j < len1; j++) {
                        if (regText.indexOf(_spstr[j]) === -1) {
                            _regText += _spstr[j];
                        } else {
                            _regText += '\\' + _spstr[j];
                        }
                    }
                    _regText += ']'
                    pattern = new RegExp(_regText, 'g');
                } else {
                    pattern = new RegExp("[^0-9A-Za-z\\s]", 'g')
                }

            }
            var _restr = restr || '';
            switch (typeArr[i]) {
                case 'special':
                    _str = _str.replace(pattern, _restr);
                    break;
                case 'html':
                    _str = _str.replace(/<\/?[^>]*>/g, _restr);
                    break;
                case 'emjoy':
                    _str = _str.replace(/[^\u4e00-\u9fa5|\u0000-\u00ff|\u3002|\uFF1F|\uFF01|\uff0c|\u3001|\uff1b|\uff1a|\u3008-\u300f|\u2018|\u2019|\u201c|\u201d|\uff08|\uff09|\u2014|\u2026|\u2013|\uff0e]/g, _restr);
                    break;
                case 'word':
                    _str = _str.replace(/[a-z]/g, _restr);
                    break;
                case 'WORD':
                    _str = _str.replace(/[A-Z]/g, _restr);
                    break;
                case 'number':
                    _str = _str.replace(/[0-9]/g, _restr);
                    break;
                case 'chinese':
                    _str = _str.replace(/[\u4E00-\u9FA5]/g, _restr);
                    break;
            }
        }
        return _str;
    },
    //取随机数
    rnd : function (n,m){
        return parseInt(Math.random()*(m-n)+n)
    },
    //补零
    toDub : function (n){
        return n<10?'0'+n:''+n;
    },
    //获取行间样式
    getStyle : function (obj,name){
        if(obj instanceof jQuery){
            return obj.attr(name)
        }else{
            alert("传入Jquery对象")
        }
    },
    //打开弹窗
    openWindow : function (trigger,popObj) {
        $(trigger).on("click",function () {
            $(popObj).show();
        })
    },
    //关闭弹窗
    closeWindow : function (trigger,popObj) {
        $(trigger).on("click",function () {
            $(popObj).hide();
        })
    },
    //将json
    objKeySort : function (arys) {
        //先用Object内置类的keys方法获取要排序对象的属性名，再利用Array原型上的sort方法对获取的属性名进行排序，newkey是一个数组
        var newkey = Object.keys(arys).sort();
        //console.log('newkey='+newkey);
        var newObj = {}; //创建一个新的对象，用于存放排好序的键值对
        for(var i = 0; i < newkey.length; i++) {
            //遍历newkey数组
            newObj[newkey[i]] = arys[newkey[i]];
            //向新创建的对象中按照排好的顺序依次增加键值对

        }
        return newObj; //返回排好序的新对象
    },
    //选项卡
    tab : function (trigger , item ){
        $(trigger).on("click",function (){
            $(this).addClass("active").siblings().removeClass("active")
            var thisIndex = $(this).index();
            $(item).eq(thisIndex).show().siblings().hide();
        })
    },
    //选择下拉
    chooseList : function ( trigger , child) {
        $(trigger).on("click",function () {
            $(this).addClass("active").siblings().removeClass("active");
            $(trigger).next("dl").toggle();
        });
        $(child).on("click",function () {
            $(trigger).html($(this).html());
            $(child).parent().hide();
        })
    },
    //PC拖拽
    pcDrag : function (obj){
        var clW = document.documentElement.clientWidth || document.body.clientWidth;
        var clH = document.documentElement.clientHeight || document.body.clientHeight;
        obj.onmousedown = function (ev){
            var oEvent = ev || event;
            var disX = oEvent.clientX - obj.offsetLeft;
            var disY = oEvent.clientY - obj.offsetTop;
            document.onmousemove = function (ev){
                var oEvent = ev || event;
                var left = oEvent.clientX - disX;
                var top = oEvent.clientY - disY;
                if (left < 0){
                    left = 0;
                }else if (left > clW - obj.offsetWidth){
                    left = clW - obj.offsetWidth;
                }
                if (top < 0){
                    top = 0;
                }else if (top > clH - obj.offsetHeight){
                    top = clH - obj.offsetHeight-1;
                }
                obj.style.left = left+'px';
                obj.style.top = top+'px';
            };
            document.onmouseup = function (){
                document.onmousemove = null;
                document.onmouseup = null;
                obj.releaseCapture && obj.releaseCapture();//releaseCapture释放鼠标信息
            };
            obj.setCapture && obj.setCapture();//setCapture捕获鼠标信息
            return false;
        };
    },
    //移动端拖拽
    mobileDrag : function (obj){

        var disX,moveX,L,T,starX,starY,starXEnd,starYEnd;

        obj.addEventListener('touchstart',function(e){

            e.preventDefault();

            disX = e.touches[0].clientX - this.offsetLeft;
            disY = e.touches[0].clientY - this.offsetTop;

            starX = e.touches[0].clientX;
            starY = e.touches[0].clientY;

        });
        obj.addEventListener('touchmove',function(e){
            L = e.touches[0].clientX - disX ;
            T = e.touches[0].clientY - disY ;

            starXEnd = e.touches[0].clientX - starX;
            starYEnd = e.touches[0].clientY - starY;

            if(L < 0){
                L = 0;
            }else if(L > document.documentElement.clientWidth - this.offsetWidth){
                L = document.documentElement.clientWidth - this.offsetWidth;
            }

            if(T < 0){
                T = 0;
            }else if(T>document.documentElement.clientHeight - this.offsetHeight){
                T = document.documentElement.clientHeight - this.offsetHeight;
            }
            moveX = L + 'px';
            moveY = T + 'px';

            this.style.left = moveX;
            this.style.top = moveY;
        });
        window.addEventListener('touchend',function(e){});
    },
    isHasAttr :	function (obj, attr) {
        if (obj && obj.hasOwnProperty(attr)) {
            return true;
        }
        return false;
    },
    /*	autoplay	speed	pagination	button	*/
    banner : function ( obj , json ) {
        var num = 0 ,timer = null;
        json = json || {};
        if (obj == null){return false}

        var $this = $(obj),
            $slide = $this.find(".slide"),
            $wrapper = $this.find(".wrapper"),
            $width = $slide.width(),
            $length = $slide.length+1,
            autoPlay = json.autoplay || 4000,
            speed = json.speed || 500,
            pagination = json.pagination,
            button = json.button,
            slt = json.slt;

        $slide.width($width);
        var firstImg = $slide.first().clone();
        $wrapper.append(firstImg).width($width*$length);

        if (slt == "yes") {
            $("#bannerBtn .slide").on("click",function(){
                var thisIndex = $(this).index();
                $wrapper.animate({
                    left: - thisIndex * $width + "px"
                },300);
            })
        }


        if (pagination === "yes"){
            $this.append("<div class='btn-list'></div>");

            for( i = 0 ; i < $length-1 ; i++){
                var model = $slide.eq(i).find("img").clone();
                $this.find(".btn-list").append(model);
                // i == 0 ? $this.find(".btn-list").append("<a class='active'>"+model+"</a>") : $this.find(".btn-list").append("<a>"+model+"</a>");
            }

            $(".btn-list a").on("click",function (){
                clearInterval(timer);
                var thisIndex = $(this).index();
                $wrapper.animate({
                    left: - thisIndex * $width + "px"
                },300);
                $(this).addClass("active").siblings().removeClass("active");
            }).on("click",function (){
                num = $(this).index();
                // tab();
            });

        }

        if (button === "yes"){
            $this.append("<a href='javascript:;' class='btn-prev'></a>");
            $this.append("<a href='javascript:;' class='btn-next'></a>");

            $(".btn-prev").on("click",function () {

                num === 0 ? num = $length-2 : num -- ;

                $wrapper.animate({left: - num * $width + "px"},300);

                round();

            });

            $(".btn-next").on("click",function () {

                num++;
                if (num == $length){
                    num = 1 ;
                    $wrapper.css({left:0});
                }
                $wrapper.animate({left: - num * $width + "px"},300);

                tab();

            })

        }

        function tab(){
            timer = setInterval(function (){
                num++;
                if (num == $length){
                    num = 1 ;
                    $wrapper.css({left:0});
                }

                $wrapper.stop().animate({left : - num * $width },speed);

                round();

            },autoPlay)
        }

        tab();

        $this.mouseover(function (){
            clearInterval(timer);
        }).mouseout(function (){
            num = $(this).index();
            tab();
        });

        function round() {
            if(num == $length - 1 ){
                $('.btn-list a').eq(0).addClass('active').siblings().removeClass('active');
            }else{
                $('.btn-list a').eq(num).addClass('active').siblings().removeClass('active');
            }
        }

    }
};